package upm.pb4agent.team5;

import jade.core.AID;
import jade.domain.FIPAException;
import jade.util.leap.ArrayList;
import jade.util.leap.List;
import jade.wrapper.StaleProxyException;
import upm.pb4agent.team5.custom.Manager;
import upm.pb4agent.team5.custom.Rower;

public class AgTeam5 extends BaseAgent {
	private static final long serialVersionUID = -8665833914609603750L;
	public final static String DF_NAME = "AgTeam5";
	
    public AgTeam5() {
		super(DF_NAME);
	}
    
	/**
     * Method executed when agent is initialized
     */
	protected void setup() {
		System.out.println(getLocalName() + ": Enters the system");

		try {
			List rowers = startRowers();
			startManager(rowers);

		} catch (StaleProxyException e) {
			System.err.println(getLocalName() + ": Agent creation failed");
		} catch (InterruptedException e) {
			System.err.println(getLocalName() + ": Thread.sleep failed");
		} catch (FIPAException e) {
			System.err.println(getLocalName() + ": DF search failed");
		}

		doDelete();
	}

	/**
	 * Start rowers and return list of their AIDs
	 * @return List Rowers AID
	 * @throws StaleProxyException
	 * @throws InterruptedException
	 * @throws FIPAException
	 */
	private List startRowers() throws StaleProxyException, InterruptedException, FIPAException {
		List rowers = new ArrayList();
		
		for (int i=0; i<4; i++) {
			AID aid = createAgent(Rower.class, Rower.DF_NAME[i], null, true);
			rowers.add(aid); // Adding rower's AID 
		}
		
		return rowers;
	}
	
	/**
	 * Start manager 
	 * @param rowers
	 * @throws StaleProxyException
	 * @throws InterruptedException
	 * @throws FIPAException
	 */
	private void startManager(List rowers) throws StaleProxyException, InterruptedException, FIPAException {
		createAgent(Manager.class, Manager.DF_NAME, new Object[] { rowers }, false);
	}
}
